package Tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:Tcp客户端
 * User: lenovo
 * Date: 2022-10-18
 * Time: 14:57
 */
public class TcpEchoClient {
    //创建一个套接字对象和服务器建立连接
    Socket socket = null;
    //提供服务器的Ip和端口号,并且与服务器进连接
    public TcpEchoClient(String serveIp,int port) throws IOException {
        this.socket = new Socket(serveIp,port);
    }
    //连接成功后,开始执行逻辑
    public void start(){
        System.out.println("客户端连接上了服务器!!!");
        Scanner scanner = new Scanner(System.in);
        //先
            try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream()){
                while (true) {
                    //1.客户端输入请求
                    System.out.println("请输入请求->:");
                    String request = scanner.next();
                    //2.将请求发送给服务器 使用输出流写网卡就是发送
                    //PrintWriter来包装输出流
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    //刷新缓存区,确保将request发送给服务器
                    printWriter.flush();

                    //3.读取服务器的响应 使用输入流读取网卡实现接收服务器的响应
                    Scanner responseScanner = new Scanner(inputStream);
                    String response = responseScanner.next();
                    //4.打印响应
                    System.out.println(response);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }


    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }


}
